package com.yanchangapp.ui.fragment.mail;

import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.yanchangapp.R;
import com.yanchangapp.adapter.CntDpAdapter;
import com.yanchangapp.adapter.CntSheepAdapter;
import com.yanchangapp.commom.AppConstant;
import com.yanchangapp.model.bean.CntUserBean;
import com.yanchangapp.model.bean.MailUserBean;
import com.yanchangapp.model.response.CntListResponse;
import com.yanchangapp.ui.activity.mail.MailHomeActivity;
import com.yanchangapp.ui.activity.mail.MailWriteActivity;
import com.yanchangapp.ui.presenter.ContactFgPresenter;
import com.yanchangapp.ui.view.ContactFgView;
import com.zxl.baselib.ui.base.BaseFragment;
import com.zxl.baselib.util.ui.UIUtils;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

public class MailContactFragment extends BaseFragment<ContactFgView, ContactFgPresenter> implements ContactFgView, CntDpAdapter.CntSelectListener {
    @BindView(R.id.ivToolbarNavigation)
    ImageView ivToolbarNavigation;
    @BindView(R.id.vToolbarDivision)
    View vToolbarDivision;
    @BindView(R.id.tvToolbarTitle)
    TextView tvToolbarTitle;
    @BindView(R.id.tv_publish_now)
    TextView tvPublishNow;
    @BindView(R.id.rvSheep)
    RecyclerView rvSheep;
    @BindView(R.id.chCheckAll)
    CheckBox mCheckboxAll;
    @BindView(R.id.checkLinear)
    LinearLayout mCheckLinear;
    @BindView(R.id.rvDepartments)
    RecyclerView rvDepartments;

    @BindView(R.id.llContent)
    LinearLayout llContent;
    @BindView(R.id.frameProgress)
    RelativeLayout frameProgress;
    @BindView(R.id.btnNextRefresh)
    TextView btnNextRefresh;
    @BindView(R.id.llErrorNetwork)
    LinearLayout llErrorNetwork;

    // 如果这样做还是不行的...
    private List<CntUserBean> mSheepBeanList;
    // 头部面包屑  Adapter
    private CntSheepAdapter mCntSheepAdapter;
    // 部门       Adapter
    private CntDpAdapter mCntDpAdapter;
    // 当前部门的数据     列表
    private List<CntUserBean> mCntDpUserList;

    // 原始数据Bean
    private CntUserBean mOriginBean;
    private int mCurrentIndex;
    private List<MailUserBean> mSelectLists;

    @Override
    public void init() {
        mSheepBeanList = new ArrayList<>();
        mCntDpUserList = new ArrayList<>();
        // 选中的数量
        mSelectLists = new ArrayList<>();
    }

    @Override
    protected int provideContentViewId() {
        return R.layout.fragment_mail_contact;
    }

    @Override
    protected ContactFgPresenter createPresenter() {
        return new ContactFgPresenter((MailHomeActivity) getActivity());
    }

    @Override
    public void initView(View rootView) {
        tvPublishNow.setVisibility(View.VISIBLE);
        tvPublishNow.setText("写信");
        tvToolbarTitle.setText("联系人");
        showLoading();
        setHeadAdapter();
        setUserAdapter();
        doListener();
        queryData();
    }

    private void showContent(){
        if (frameProgress.getVisibility() == View.VISIBLE){
            frameProgress.setVisibility(View.GONE);
        }

        if (llContent.getVisibility() == View.GONE){
            llContent.setVisibility(View.VISIBLE);
        }

        if (llErrorNetwork.getVisibility() == View.VISIBLE){
            llErrorNetwork.setVisibility(View.GONE);
        }
    }

    private void showErr(){
        if (frameProgress.getVisibility() == View.VISIBLE){
            frameProgress.setVisibility(View.GONE);
        }

        if (llContent.getVisibility() == View.VISIBLE){
            llContent.setVisibility(View.GONE);
        }

        if (llErrorNetwork.getVisibility() == View.GONE){
            llErrorNetwork.setVisibility(View.VISIBLE);
        }
    }

    private void showLoading(){
        if (frameProgress.getVisibility() == View.GONE){
            frameProgress.setVisibility(View.VISIBLE);
        }

        if (llContent.getVisibility() == View.VISIBLE){
            llContent.setVisibility(View.GONE);
        }

        if (llErrorNetwork.getVisibility() == View.VISIBLE){
            llErrorNetwork.setVisibility(View.GONE);
        }
    }

    private void setHeadAdapter() {
        rvSheep.setLayoutManager(new LinearLayoutManager(_mActivity, LinearLayoutManager.HORIZONTAL, false));
        mCntSheepAdapter = new CntSheepAdapter(R.layout.item_contact_head_sheep, mSheepBeanList);
        rvSheep.setAdapter(mCntSheepAdapter);
    }

    // 初始化用户信息的Adapter
    private void setUserAdapter() {
        // 部门
        LinearLayoutManager mLlDpManager = new LinearLayoutManager(_mActivity, LinearLayoutManager.VERTICAL, false);
        mLlDpManager.setSmoothScrollbarEnabled(true);
        mLlDpManager.setAutoMeasureEnabled(true);
        rvDepartments.setHasFixedSize(true);
        rvDepartments.setNestedScrollingEnabled(false);
        rvDepartments.setLayoutManager(mLlDpManager);
        mCntDpAdapter = new CntDpAdapter(R.layout.item_contact_dp, mCntDpUserList, this);
        rvDepartments.setAdapter(mCntDpAdapter);
    }

    @Override
    public void initData() {
    }

    private void queryData() {
        showLoading();
        mPresenter.queryMailContactLists();
    }

    private void doListener() {
        ivToolbarNavigation.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                _mActivity.finish();
            }
        });
        // 面包屑点击事件...
        mCntSheepAdapter.setOnItemClickListener((adapter, view, position) -> {
            mCurrentIndex = position;
            if (position != mSheepBeanList.size() - 1) {
                // 移除面包屑 并进行刷新
                int size = mSheepBeanList.size() - 1 - position;
                for (int i = 0; i < size; i++) {
                    mSheepBeanList.remove(mSheepBeanList.size() - 1);
                }
                mCntSheepAdapter.notifyDataSetChanged();
                mCntDpUserList.clear();
                mCntDpUserList.addAll(mSheepBeanList.get(position).getChildren());
                // 设置cb是否选中
                mCntDpAdapter.notifyDataSetChanged();
                setCheckboxState();
            }
        });
        mCntDpAdapter.setOnItemChildClickListener((adapter, view, position) -> {
            if (view.getId() == R.id.tvDpNext) {
                // 展示下一级别的数据
                mCurrentIndex = mCurrentIndex + 1;
                CntUserBean cntUserBean = mCntDpUserList.get(position);
                List<CntUserBean> list = cntUserBean.getChildren();
                mCntDpUserList.clear();
                mCntDpUserList.addAll(list);
                mCntDpAdapter.notifyDataSetChanged();
                // 进行设置
                mCheckboxAll.setChecked(cntUserBean.isChecked());
                mSheepBeanList.add(cntUserBean);
                mCntSheepAdapter.notifyDataSetChanged();
            }
        });

        mCntDpAdapter.setOnItemClickListener((adapter, view, position) -> view.findViewById(R.id.cbDp).performClick());


        mCheckboxAll.setOnClickListener(v -> {
            checkNode(mSheepBeanList.get(mCurrentIndex), mCheckboxAll.isChecked());
            mCntDpAdapter.notifyDataSetChanged();
        });

        mCheckLinear.setOnClickListener(v -> mCheckboxAll.performClick());

        tvPublishNow.setOnClickListener(v -> jumpToWriteNow());

        btnNextRefresh.setOnClickListener(v -> queryData());
    }

    @Override
    public void initListener() {
    }

    private void jumpToWriteNow() {
        mSelectLists.clear();
        // 如果选中数量为0 那么直接返回即可
        if (mOriginBean == null ||  mOriginBean.getSelectedSize() == 0) {
            MailWriteActivity.show(getActivity(), mSelectLists);
            return;
        }
        addSelectedLists(mOriginBean);
        MailWriteActivity.show(getActivity(), mSelectLists);
    }

    /**
     * 递归获取已经选择的列表
     *
     * @param cntUserBean
     */
    private void addSelectedLists(CntUserBean cntUserBean) {
        if (cntUserBean.getFlag()
                == AppConstant.FLAG_IS_USER && cntUserBean.isChecked()) {
            mSelectLists.add(new MailUserBean(cntUserBean.getAddress(), cntUserBean.getName(), cntUserBean.getUsername()));
        }
        for (int i = 0; i < cntUserBean.getChildren().size(); i++) {
            addSelectedLists(cntUserBean.getChildren().get(i));
        }
    }


    private void setCheckboxState() {
        mCheckboxAll.setChecked(mSheepBeanList.get(mCurrentIndex).isChecked());
    }

    //  node....结点开始

    private void checkNode(CntUserBean cntUserBean, boolean isChecked) {
        cntUserBean.setChecked(isChecked);
        checkChildren(cntUserBean, isChecked);
        unCheckNode(cntUserBean, isChecked);
        checkedSize(cntUserBean);
    }

    private void checkedSize(CntUserBean cntUserBean) {
        if (cntUserBean.getFlag() == AppConstant.FLAG_IS_USER) {
            setNodeSize(cntUserBean);
        } else {
            // 如果是选中的状态...
            boolean selected = cntUserBean.isChecked();
            if (selected) {
                // 设置完全选中数量
                int addSize = cntUserBean.getSum() - cntUserBean.getSelectedSize();
                cntUserBean.setSelectedSize(cntUserBean.getSum());
                // 父亲有问题
                setChangeParentSize(cntUserBean, addSize, cntUserBean.getId());
                setAddChildrenSize(cntUserBean);
            } else {
                // 设置当前选中数量
                cntUserBean.setSelectedSize(0);
                int addSize = cntUserBean.getSelectedSize() - cntUserBean.getSum();
                setChangeParentSize(cntUserBean, addSize, cntUserBean.getId());
                setMinChildrenSize(cntUserBean);
            }
        }
    }

    // 设置子节点数量减少
    private void setMinChildrenSize(CntUserBean cntUserBean) {
        for (int i = 0; i < cntUserBean.getChildren().size(); i++) {
            CntUserBean cntUserBeanInner = cntUserBean.getChildren().get(i);
            cntUserBeanInner.setSelectedSize(0);
            setMinChildrenSize(cntUserBeanInner);
        }
    }

    // 设置子节点数量增加
    private void setAddChildrenSize(CntUserBean cntUserBean) {
        for (int i = 0; i < cntUserBean.getChildren().size(); i++) {
            CntUserBean cntUserBeanInner = cntUserBean.getChildren().get(i);
            cntUserBeanInner.setSelectedSize(cntUserBeanInner.getSum());
            setAddChildrenSize(cntUserBeanInner);
        }
    }

    /**
     * 设置父亲节点数量改变
     *
     * @param cntUserBean
     * @param changeSize
     * @param currentID
     */
    private void setChangeParentSize(CntUserBean cntUserBean, int changeSize, long currentID) {
        if (cntUserBean.getId() != currentID) {
            cntUserBean.setSelectedSize(cntUserBean.getSelectedSize() + changeSize);
        }
        if (cntUserBean.getParent() != null) {
            setChangeParentSize(cntUserBean.getParent(), changeSize, currentID);
        }
    }

    public void setNodeSize(CntUserBean n) {
        if (null == n) {
            return;
        }
        int size = 0;
        if (n.getChildren().size() == 0) {
            if (n.isChecked()) {
                size = 1;
            } else {
                size = 0;
            }
        } else {
            for (int i = 0; i < n.getChildren().size(); i++) {
                size = size + n.getChildren().get(i).getSelectedSize();
            }
        }
        n.setSelectedSize(size);
        if (n.getParent() != null) {
            setNodeSize(n.getParent());
        }
    }

    /**
     * 设置子节点的选中状态
     *
     * @param cntUserBean
     * @param isChecked
     */
    private void checkChildren(CntUserBean cntUserBean, boolean isChecked) {
        for (int i = 0; i < cntUserBean.getChildren().size(); i++) {
            cntUserBean.getChildren().get(i).setChecked(isChecked);
            checkChildren(cntUserBean.getChildren().get(i), isChecked);
        }
    }

    /**
     * 设置父节点的选中状态
     *
     * @param n
     * @param isChecked
     */
    private void unCheckNode(CntUserBean n, boolean isChecked) {
        if (n == null) {
            return;
        }
        boolean flag = false;
        // 当前节点设置为true或者false
        n.setChecked(isChecked);
        if (n.getParent() != null) {
            for (int i = 0; i < n.getParent().getChildren().size(); i++) {
                // 除了当前的Item,如果儿子都是true
                // 那么则设置父亲
                // 如果有一个false则不设置
                if ((n.getParent().getChildren().get(i)) != null && (n.getParent().getChildren().get(i).getId().intValue())
                        != n.getId() && (!n.getParent().getChildren().get(i).isChecked())) {
                    flag = true;
                    break;
                }
            }
            if (!flag) {
                unCheckNode(n.getParent(), isChecked);
            }
        }
    }

    //  node....结点结束

    @Override
    public void queryContactsSuccess(CntListResponse cntListResponse) {
        mOriginBean = cntListResponse.getData();
        mSheepBeanList.clear();
        mCntDpUserList.clear();
        // 进行初始化的数据...
        setOriginBean(mOriginBean);
        mCurrentIndex = 0;
        mCntDpUserList.addAll(mOriginBean.getChildren());
        mSheepBeanList.add(mOriginBean);
        mCntSheepAdapter.notifyDataSetChanged();
        // 进行列表刷新
        mCntDpAdapter.notifyDataSetChanged();
        showContent();
    }

    /**
     * 设置原始数据
     */
    private void setOriginBean(CntUserBean currentBean) {
        for (int i = 0; i < currentBean.getChildren().size(); i++) {
            CntUserBean bean = currentBean.getChildren().get(i);
            bean.setParent(currentBean);
            setOriginBean(bean);
        }
    }

    @Override
    public void queryContactFailure(String err) {
        UIUtils.showToast(err);
        showErr();
    }

    @Override
    public void onCheckChangedListener(int position, boolean state, CntUserBean cntUserBean) {
        checkNode(cntUserBean, state);
        mCheckboxAll.setChecked(cntUserBean.getParent().isChecked());
        mCntDpAdapter.notifyDataSetChanged();
    }

}
